// ignore_for_file: file_names, must_be_immutable, constant_identifier_names, slash_for_doc_comments, avoid_unnecessary_containers, prefer_const_constructors, unnecessary_cast, sized_box_for_whitespace, prefer_function_declarations_over_variables, overridden_fields, annotate_overrides, prefer_const_literals_to_create_immutables, unnecessary_null_comparison, deprecated_member_use

import 'dart:io';
import 'dart:typed_data';

import 'package:dio/dio.dart';
import 'package:flutter_wifi/entity/TrackEntity.dart';
import 'package:flutter_wifi/page/WebBasePage.dart';
import 'package:flutter_wifi/upload/MusicUploadTask.dart';
import 'package:mybase/base/tool/api/ApiUtils.dart';
import 'package:mybase/base/tool/queue2/FFMultiTaskManager.dart';
import 'package:mybase/base/widget/progress/FFProgressManager.dart';

class MusicFileManager {
  // 单例公开访问点
  factory MusicFileManager() => _sharedInstance();

  // 静态、同步、私有访问点
  static MusicFileManager _sharedInstance() {
    return _instance;
  }

  // 静态私有成员，没有初始化
  static final MusicFileManager _instance = MusicFileManager._();

  // 私有构造函数
  MusicFileManager._() {}

  addTask({
    required Uint8List data,
    required String fileName,
    required WebBasePageGetx getx,
    required int size,
  }) {
    // 上传文件
    MusicUploadTask task = MusicUploadTask(
      name: fileName,
      params: {
        "data": data,
        "fileName": fileName,
      },
      execute: (dynamic obj, map) async {
        MusicUploadTask task = obj as MusicUploadTask;

        Uint8List data = map!['data'] as Uint8List;
        String fileName = map['fileName'] as String;

        final dio = Dio();
        FormData formData = FormData.fromMap({
          "files": await MultipartFile.fromBytes(data, filename: fileName),
        });

        var notifier = FFProgressManager().getValueNotifier(fileName);
        notifier?.value = FFNotifierVo(
          type: FFNotifierVoType.progress,
          percent: 0.0,
        );

        try {
          final response = await dio.post(
            '${ApiUtils.appApi.env_product}upload',
            data: formData,
            options: Options(
              headers: {
                HttpHeaders.contentTypeHeader: "multipart/form-data",
              },
              responseType: ResponseType.json,
            ),
            onSendProgress: (int sent, int total) {
              print("文件 $fileName 进度 = ${(sent * 1.0 / total * 100).toStringAsFixed(0)}%");
              notifier?.value = FFNotifierVo(
                type: FFNotifierVoType.progress,
                percent: sent * 1.0 / total,
              );
            },
          );
          if (response.statusCode == 200) {
            print('文件上传完成：$fileName');
            notifier?.value = FFNotifierVo(
              type: FFNotifierVoType.finish,
            );
            getx.completeCount++;
            getx.update();
          } else {
            print('文件上传失败：$fileName, code = ${response.statusCode}');
            notifier?.value = FFNotifierVo(
              type: FFNotifierVoType.error,
            );
          }
        } catch (e) {
          print('文件上传失败: $fileName, error = $e');
          notifier?.value = FFNotifierVo(
            type: FFNotifierVoType.error,
          );
        }
      },
    );
    FFProgressManager().setValueNotifier(fileName, FFNotifier(FFNotifierVo(type: FFNotifierVoType.none)));
    getx.uploadList.add(task);
    getx.update();
    FFMultiTaskManager().addTask(task);
  }
}
